"""
RJ45接口使用示例

演示如何使用RJ45接口与雷达设备通信
"""

import sys
import time
import json
from pathlib import Path

# 添加项目路径
sys.path.insert(0, str(Path(__file__).parent.parent))

from radar_client import RadarClient
from radar_client.config import RadarConfig


def basic_usage_example():
    """基础使用示例"""
    print("=== RJ45基础使用示例 ===")

    # 创建雷达客户端
    client = RadarClient()

    try:
        # 连接RJ45接口
        print("正在连接RJ45接口...")
        client.connect_rj45({
            'ip_address': '192.168.1.100',
            'data_port': 50001,
            'control_port': 50002
        })

        # 获取连接信息
        connection_info = client.get_connection_info()
        print(f"连接信息: {json.dumps(connection_info, indent=2, ensure_ascii=False)}")

        # 获取雷达状态
        print("\n获取雷达状态...")
        status = client.get_status()
        print(f"雷达状态: {status.to_dict()}")

        # 启动扫描
        print("\n启动雷达扫描...")
        result = client.start_scan()
        print(f"启动扫描结果: {result}")

        # 获取目标数据
        print("\n获取目标数据...")
        targets = client.get_targets()
        print(f"发现 {len(targets)} 个目标:")
        for i, target in enumerate(targets):
            print(f"  目标 {i+1}: {target.to_dict()}")

        # 停止扫描
        print("\n停止雷达扫描...")
        result = client.stop_scan()
        print(f"停止扫描结果: {result}")

    except Exception as e:
        print(f"错误: {e}")

    finally:
        # 断开连接
        client.disconnect()
        print("连接已断开")


def callback_example():
    """回调函数使用示例"""
    print("\n=== 回调函数使用示例 ===")

    def data_callback(data):
        print(f"接收到数据: {len(data)} 字节")

    def target_callback(targets):
        print(f"检测到 {len(targets)} 个目标")
        for target in targets:
            print(f"  目标ID: {target.target_id}, 距离: {target.range_val:.2f}m")

    def status_callback(status):
        print(f"雷达状态更新: 温度={status.temperature:.1f}°C, 电压={status.voltage:.2f}V")

    def error_callback(error):
        print(f"发生错误: {error}")

    client = RadarClient()

    try:
        # 设置回调函数
        client.set_data_callback(data_callback)
        client.set_target_callback(target_callback)
        client.set_status_callback(status_callback)
        client.set_error_callback(error_callback)

        # 连接
        client.connect_rj45()

        # 启动扫描并等待数据
        client.start_scan()
        print("等待目标数据...")
        time.sleep(5)

        # 停止扫描
        client.stop_scan()

    except Exception as e:
        print(f"错误: {e}")

    finally:
        client.disconnect()


def configuration_example():
    """配置管理示例"""
    print("\n=== 配置管理示例 ===")

    # 创建示例配置文件
    config_file = Path(__file__).parent / "radar_config.json"
    RadarConfig.create_sample_config(str(config_file))

    # 使用配置文件
    client = RadarClient(config_file=str(config_file))

    try:
        # 连接
        client.connect_rj45()

        # 修改配置
        client.update_config({
            'rj45': {'timeout': 2000},
            'general': {'log_level': 'DEBUG'}
        })

        # 保存配置
        client.save_config()

        # 获取状态
        status = client.get_status()
        print(f"雷达状态: {status.to_dict()}")

    except Exception as e:
        print(f"错误: {e}")

    finally:
        client.disconnect()


def context_manager_example():
    """上下文管理器使用示例"""
    print("\n=== 上下文管理器使用示例 ===")

    try:
        with RadarClient() as client:
            client.connect_rj45()

            # 获取状态
            status = client.get_status()
            print(f"雷达状态: {status.to_dict()}")

            # 获取目标数据
            targets = client.get_targets()
            print(f"检测到 {len(targets)} 个目标")

    except Exception as e:
        print(f"错误: {e}")


def error_handling_example():
    """错误处理示例"""
    print("\n=== 错误处理示例 ===")

    def handle_error(error):
        print(f"错误处理: {type(error).__name__}: {error}")

    client = RadarClient()
    client.set_error_callback(handle_error)

    try:
        # 尝试连接错误的IP
        client.connect_rj45({
            'ip_address': '192.168.999.999',
            'timeout': 1000
        })

    except Exception as e:
        print(f"连接失败: {e}")

    # 尝试连接正确的IP但使用错误的端口
    try:
        client.connect_rj45({
            'ip_address': '192.168.1.1',
            'data_port': 99999
        })

    except Exception as e:
        print(f"参数错误: {e}")

    finally:
        client.disconnect()


if __name__ == "__main__":
    """运行所有示例"""
    print("RJ45雷达客户端示例程序")
    print("=" * 50)

    # 运行示例
    basic_usage_example()
    callback_example()
    configuration_example()
    context_manager_example()
    error_handling_example()

    print("\n" + "=" * 50)
    print("示例程序运行完成")